<?php
/**
 * Created by PhpStorm.
 * User: kervin
 * Date: 2018/7/18
 * Time: 14:13
 */

namespace app\admin\controller;

use \think\Db;
use \think\Cookie;
use \think\Session;
use think\Exception;
use think\Request;
use app\admin\controller\Permissions;
use app\admin\model\Admin as adminModel;//管理员模型
use app\admin\model\Loginlog;
class Tools extends Permissions{

    /**
     * Excel一键导出
     */
    public function excel()
    {
        if ($this->request->isPost()) {
//            $header = ['用户ID', '登录IP', '登录地点', '登录浏览器', '登录操作系统', '登录时间'];
            $header = ['操作菜单id','操作者id', '操作ip', '操作关联id', '操作时间'];
            $data = Db::name("admin_log")
                ->field("id", true)
                ->order("id desc")
//                ->limit(20)
                ->fetchSql(false)
                ->select();
            if ($error = \Excel::export($header, $data, "Excel导出", '2007')) {
                throw new Exception($error);
            }
        } else {
            return $this->view->fetch();
        }
    }

    /**
     * 下载文件
     * @return mixed
     */
    public function download()
    {
        if ($this->request->param('file')) {
            return \File::download("../README.md");
        } else {
            return $this->view->fetch();
        }
    }


    /**
     * 下载远程图片
     * @return mixed
     */
    public function downloadImage()
    {
        if (Request::instance()->isPost()) {
            $url = $this->request->post("url");
            if (substr($url, 0, 4) != "http") {
                return ajax_return_adv_error("URL非法");
            }
            $name = "./tmp/" . get_random();
//            is_dir($name) OR mkdir($name, 0777, true);
//            is_file($name) OR fclose(fopen($name, 'w'));
            $filename = \File::downloadImage($url, $name);
            if (!$filename) {
                return ajax_return_adv_error($filename);
            } else {
                $url = $this->request->root() . substr($filename, 1);
//                return ajax_return_adv("下载成功", '', "图片下载成功，<a href='{$url}' target='_blank' class='c-blue'>点击查看</a><br>{$url}");
                return $this->success("图片下载成功，<a href='{$url}' target='_blank' class='c-blue'>点击查看</a><br>{$url}");
            }
        } else {
            return $this->view->fetch();
        }
    }

    /**
     * 百度编辑器
     * @return mixed
     */
    public function ueditor()
    {
        return $this->view->fetch();
    }

    /**
     * 七牛上传
     * @return mixed
     */
    public function qiniu()
    {
        if ($this->request->isPost()) {
            return '<script>parent.layer.alert("仅做演示")</script>';
            /*$result = \Qiniu::instance()->upload();
            p($result);*/
        } else {
            return $this->view->fetch();
        }
    }

    /**
     * ID加密
     * @return mixed
     */
    public function hashids()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post("id_str");
            if(empty($id) && isset($id) ){
                return $this->success("请输入字符串!");
            }
           ;
//            $hashids = \Hashids\Hashids::instance(8, "tpadmin");
//            $encode_id = $hashids->encode($id); //加密
//            $decode_id = $hashids->decode($encode_id); //解密
//            $htmlStr = '<span>加密字符串:'+$encode_id+ '</span><br><span>解密字符串：'+ " $decode_id "+'</span><br>';
//            $htmlStr = '<span>加密后字符串:'+ md5($id) + '</span>';
            return $this->success(md5($id));
        } else {
            return $this->view->fetch();
        }
    }

    /**
     * 丰富弹层
     */
    public function layer()
    {
        return $this->view->fetch();
    }

    /**
     * 表格溢出
     */
    public function tableFixed()
    {
        return $this->view->fetch();
    }

    /**
     * 图片上传回调
     */
    public function imageUpload()
    {
        return $this->view->fetch();
    }

    /**
     * 上传图片
     * @return \think\response\Json
     */
    public function uploadImage($module='demo',$use='demo_thumb'){
        $file = request()->file('image');
        if (!empty($file)) {
            $module = $this->request->has('module') ? $this->request->param('module') : $module;//模块
            $info = $file->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads'. DS . $module . DS . $use);
            if ($info) {
                //写入到附件表
                $data = [];
                $data['module'] = $module;
                $data['filename'] = $info->getFilename();//文件名
                $data['filepath'] = DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();//文件路径
                $data['fileext'] = $info->getExtension();//文件后缀
                $data['filesize'] = $info->getSize();//文件大小
                $data['create_time'] = time();//时间
                $data['uploadip'] = $this->request->ip();//IP
                $data['user_id'] = Session::has('admin') ? Session::get('admin') : 0;
                if($data['module'] = 'admin') {
                    //通过后台上传的文件直接审核通过
                    $data['status'] = 1;
                    $data['admin_id'] = $data['user_id'];
                    $data['audit_time'] = time();
                }
                $data['use'] = $this->request->has('use') ? $this->request->param('use') : $use;//用处
                $res['id'] = Db::name('attachment')->insertGetId($data);
                $res['src'] = DS . 'uploads' . DS . $module . DS . $use . DS . $info->getSaveName();
                $res['code'] = 2;
//                addlog($res['id']);//记录日志
                return $this->success("上传成功","",$res['src']);
            } else {
//                return json(['code' => 403, 'message' => lang('error_4010'), 'data' => []]);
                return $this->error("上传失败");
            }
        } else {
//            return json(['code' => 402, 'message' => lang('error_4002'), 'data' => []]);
            return $this->error("上传失败");
        }
    }


    /**
     * 生成唯一标识
     */
    public function uniqidCode()
    {
        $uniqidCode =md5(uniqid(md5(microtime(true)), true));
        if(empty($uniqidCode) && !isset($uniqidCode)){
            return $this->success("生成唯一标识失败！");
        }
        return $this->success($uniqidCode);
    }

    /**
     * 二维码生成
     */
    public function qrCode()
    {

        if ($this->request->isPost()) {
            $url = $this->request->post("qrcode_url");
            if(empty($url) && isset($url) ){
                return $this->success("请输入Url地址");
            }
            return $this->success(md5($url));
        } else {
            return $this->view->fetch();
        }
    }




    public function Demo(){
//        $ip = $this->request->ip();
        $ip = '116.25.147.219';    //广东省深圳市 电信
//        $ip = '111.186.116.208';  //上海市宝山区 教育网
//        $ip = "218.192.3.42";     //广东省广州市 教育网
//        113.118.187.130
//        $ip_return = getIPLocation($ip);//将ip传入进来
//        dump($ip_return);//打印结果

//        $ip_address = getCurl();
//        dump($ip_address);

//        $ip = '117.25.13.123';

//        $datatype = 'txt';
//        $url = 'http://api.ip138.com/query/?ip='.$ip.'&datatype='.$datatype;
//        $header = array('token:00d5cb1fac5dc5cbfe2ff218292a2dfd33');
//        echo getIpData($url,$header);
        $ipads = \ChaXun::find($ip);
        dump($ipads);
    }

}